<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<%
		// 设置中文乱码问题，utf-8与网页编码对应 
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String remember = request.getParameter("remember");

		// 1. 加载驱动
		Class.forName("com.mysql.cj.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/ch04_students?useUnicode=true&characterEncoding=utf-8";
		// 2. 建立连接
		Connection con = DriverManager.getConnection(url, "root", "123456");
		String sql = "select * from user where username =? and password =? ";
		// 3. 创建Statement
		PreparedStatement stm = con.prepareStatement(sql);
		stm.setString(1, username);
		stm.setString(2, password);
		// 4. 执行SQL语句
		ResultSet res = stm.executeQuery();
		// 5. 处理结果
		String name = null;
		String pwd = null;
		while (res.next()) {
			int id = res.getInt("id");
			name = res.getString("username");
			pwd = res.getString("password");
			break;
		}
		System.out.println("name = " + name);
		System.out.println("pwd = " + pwd);
		// 6. 释放资源
		res.close();
		stm.close();
		con.close();

		// 判断用户名与密码是否正确
		//if ("admin".equals(username) && "123456".equals(password)) {
		if (name != null) {
			session.setAttribute("username", username);
			application.setAttribute("username", username);

			if ("true".equals(remember)) {
				Cookie c = new Cookie("remember", username);
				// 设置Cookie有效时间为3600秒
				c.setMaxAge(3600);
				response.addCookie(c);
			} else {
				// 清除Cookie
				Cookie[] cookies = request.getCookies();
				if (cookies != null && cookies.length > 0) {
					for (Cookie c : cookies) {
						if (c.getName().equals("remember")) {
							c.setMaxAge(0);
							response.addCookie(c);
						}
					}
				}
			}
			session.removeAttribute("error");
			response.sendRedirect("index.jsp");
		} else {
			session.setAttribute("error", "用户名或密码错误");
			response.sendRedirect("login.jsp");
		}
	%>
</body>
</html>

